package com.stylefeng.guns.modular.hhtb.util;

import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 */
@SuppressWarnings("all")
public class StringUtils {

	/**
	 * List去重
	 * @param list
	 * @return
	 */
	public static List removeDuplicate(List list) {
		HashSet h = new HashSet(list);
		list.clear();
		list.addAll(h);
		return list;
	}
	
	/**
     * 生成订单号
     * @param sign
     * 商城订单是2。
	 * 申请积分订单是a，
	 * 赠送积分订单是1.
	 * 充值订单是7.
	 * 代理申请订单4.
	 * 用户升级订单3
	 * 猫币转换订单编号6
	 * 第三方支付验证产生的订单号b    
	 * 赎回基本业务逻辑处理订单5  
	 * 购买牌匾订单d   
	 * 第三方支付发送参数内部业务订单号z
     * @return
     */
    public static String getOrderIdByTime(String sign) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<5;i++){
            result+=random.nextInt(10);
        }
        return sign+newDate+result;
    }

	/** 记录日志 */
	private static Logger logger = LoggerFactory.getLogger(StringUtils.class);
	/**定义escape相关常量*/
	private static String[] hex = { "00", "01", "02", "03", "04", "05", "06",
			"07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11",
			"12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C",
			"1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27",
			"28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32",
			"33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D",
			"3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48",
			"49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53",
			"54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E",
			"5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69",
			"6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74",
			"75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
			"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A",
			"8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95",
			"96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0",
			"A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB",
			"AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6",
			"B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1",
			"C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC",
			"CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7",
			"D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2",
			"E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED",
			"EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8",
			"F9", "FA", "FB", "FC", "FD", "FE", "FF" };
	/**定义escape相关常量*/
	private static byte[] val = { 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01, 0x02,
			0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F,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0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F };

	/**
	 * 编码,模拟js的escape函数.<br>
	 * escape不编码字符有69个：*+-./@_0-9a-zA-Z
	 * 
	 * @param s  字符串
	 * @return 转义后的字符串或者null
	 */
	public static String escape(String s) {
		if (s == null) {
			return null;
		}
		StringBuffer sbuf = new StringBuffer();
		int len = s.length();
		for (int i = 0; i < len; i++) {
			int ch = s.charAt(i);
			if ('A' <= ch && ch <= 'Z') {
				sbuf.append((char) ch);
			} else if ('a' <= ch && ch <= 'z') {
				sbuf.append((char) ch);
			} else if ('0' <= ch && ch <= '9') {
				sbuf.append((char) ch);
			} else if (ch == '*' || ch == '+' || ch == '-' || ch == '/'
					|| ch == '_' || ch == '.' || ch == '@') {
				sbuf.append((char) ch);
			} else if (ch <= 0x007F) {
				sbuf.append('%');
				sbuf.append(hex[ch]);
			} else {
				sbuf.append('%');
				sbuf.append('u');
				sbuf.append(hex[(ch >>> 8)]);
				sbuf.append(hex[(0x00FF & ch)]);
			}
		}
		return sbuf.toString();
	}

	/**
	 * 解码,模拟js的unescape函数. 说明：本方法保证 不论参数s是否经过escape()编码，均能得到正确的“解码”结果
	 * 
	 * @param s
	 * @return
	 */
	public static String unescape(String s) {
		if (s == null) {
			return null;
		}
		StringBuffer sbuf = new StringBuffer();
		int i = 0;
		int len = s.length();
		while (i < len) {
			int ch = s.charAt(i);
			if ('A' <= ch && ch <= 'Z') {
				sbuf.append((char) ch);
			} else if ('a' <= ch && ch <= 'z') {
				sbuf.append((char) ch);
			} else if ('0' <= ch && ch <= '9') {
				sbuf.append((char) ch);
			} else if (ch == '*' || ch == '+' || ch == '-' || ch == '/'
					|| ch == '_' || ch == '.' || ch == '@') {
				sbuf.append((char) ch);
			} else if (ch == '%') {
				int cint = 0;
				if ('u' != s.charAt(i + 1)) {
					cint = (cint << 4) | val[s.charAt(i + 1)];
					cint = (cint << 4) | val[s.charAt(i + 2)];
					i += 2;
				} else {
					cint = (cint << 4) | val[s.charAt(i + 2)];
					cint = (cint << 4) | val[s.charAt(i + 3)];
					cint = (cint << 4) | val[s.charAt(i + 4)];
					cint = (cint << 4) | val[s.charAt(i + 5)];
					i += 5;
				}
				sbuf.append((char) cint);
			} else {
				sbuf.append((char) ch);
			}
			i++;
		}
		return sbuf.toString();
	}
	/**
	 * 封装对明文进行Base64编码，并在编码前对明文进行escape转码
	 * @param mingwen
	 * @param times
	 * @return
	 */
	public static String encodeBase64(String mingwen ,int times){
		if(StringUtils.isBlank(mingwen))
			return "";
		String result = StringUtils.escape(mingwen);
		for(int i = 1 ; i <= times; i++){
			try {
				result = Base64.encodeBase64String(result.getBytes("utf-8"));
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}
	
	/**
	 * 封装对密文进行Base64解码，默认对解码后的明文进行unescape转码
	 * @param miwen	密文
	 * @param times	解码次数
	 * @return
	 */
	public static String decodeBase64(String miwen,int times){
		if(StringUtils.isBlank(miwen))
			return "";
		String result = miwen;
		for(int i = 1 ; i <= times; i++){
			try {
				result = new String(Base64.decodeBase64(result.getBytes("utf-8")));
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}
		return StringUtils.unescape(result);
	}
	
	/**
	 * 是否为空判断(trim)
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isBlank(String str) {
		return str == null || "".equals(str.trim());
	}
	
	/**
	 * 是否为空判断(trim)
	 * 
	 * @param obj
	 * @return
	 */
    public static boolean isBlank(Object obj){
        if (obj == null)
            return true;
        if (obj instanceof CharSequence)
            return ((CharSequence) obj).toString().trim().equals("");
        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();
        if (obj instanceof Map)
            return ((Map) obj).isEmpty();
        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }
    
	/**
	 * 是否为空判断(无trim)
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
			return str == null || "".equals(str);
	}

	
	/**
	 * 是否为空判断
	 * 
	 * @param obj
	 * @return
	 */
    public static boolean isEmpty(Object obj){
        if (obj == null)
            return true;
        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;
        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();
        if (obj instanceof Map)
            return ((Map) obj).isEmpty();
        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

	/**
	 * 字段串数组第一组不为空
	 * 
	 * @param ss
	 * @return
	 */
	public static boolean firstNotEmpty(final String[] ss) {
		return ss != null && ss.length > 0 && ss[0] != null
				&& ss[0].length() > 0;
	}

	/**
	 * 将Object型转换为字符串
	 * 
	 * @param
	 * @return
	 */
	public static String valueOf(Object o) {
		if (o == null) {
			return null;
		}
		String s = null;
		if (o instanceof Number) {
			s = String.valueOf(o);
		} else {
			s = o.toString();
		}
		return s;
	}

	/**
	 * 取数组中的第一组值
	 * 
	 * @param obj
	 * @return
	 */
	public static String getFirstString(Object obj) {
		if (obj == null) {
			return "";
		}
		String s = null;
		if (obj instanceof String[]) {
			String[] ss = (String[]) obj;
			s = ss[0];
		} else if (obj instanceof String) {
			s = (String) obj;
		} else {
			s = obj.toString();
		}
		return s;
	}

	/**
	 * 获取数组的第一个元素，并且作了字符串null、""的判断，这两种情况都处理为null
	 * 
	 * @param obj
	 * @return
	 */
	public static String getFirstStr(Object obj) {
		if (obj == null) {
			return null;
		}
		String tmp = null;
		if (obj instanceof String[]) {
			String[] ss = (String[]) obj;
			tmp = ss[0];
		} else if (obj instanceof String) {
			tmp = (String) obj;
		}
		if ("".equals(tmp)) {
			tmp = null;
		}
		return tmp;
	}

	/**
	 * 功能描述: 驼峰字符串转换成下划线连接<br>
	 * 例如: nextValueMySql 转换为 next_value_my_sql
	 * 
	 * @param param
	 * @return
	 */
	public static String camelVunderline(String param) {
		Pattern p = Pattern.compile("[A-Z]");
		if (param == null || param.equals("")) {
			return "";
		}
		StringBuilder builder = new StringBuilder(param);
		Matcher mc = p.matcher(param);
		int i = 0;
		while (mc.find()) {
			builder.replace(mc.start() + i, mc.end() + i, "_"
					+ mc.group().toLowerCase());
			i++;
		}
		if ('_' == builder.charAt(0)) {
			builder.deleteCharAt(0);
		}
		return builder.toString();
	}

	/**
	 * 将Null处理为空字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String toEmpty(String str) {
		if (str == null) {
			return "";
		}
		return str;
	}

	/**
	 * 删除最后的逗号
	 */
	public static StringBuilder removeLastChar(String sb) {
		if (sb.trim().endsWith(",")) {
			sb = sb.substring(0, sb.lastIndexOf(","));
		}
		return new StringBuilder(sb);
	}

	/**
	 * 去掉连接线的UUID
	 * 
	 * @return
	 */
	public static String getUuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 判断字符串是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		return isNum.matches();
	}

	/**
	 * 删除字符串中的空白
	 */
	public static String removeBlank(String sb) {
		sb = sb.replaceAll("\\s*", "");
		return sb;
	}

	/**
	 * 验证出生年月(19/20开头四位数字，0-12月)
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkBirthday(String str) {
		Pattern pattern = Pattern.compile("^(19|20)\\d{2}(0[1-9]|1[0-2])$");
		Matcher isTrue = pattern.matcher(str);
		return isTrue.matches();
	}

	/**
	 * 验证E-mail
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkEmail(String str) {
		Pattern pattern = Pattern
				.compile(
						"^([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\\.][a-z0-9]{2,4}([\\.][a-z]{2,3})?$",
						Pattern.CASE_INSENSITIVE);
		Matcher isTrue = pattern.matcher(str);
		return isTrue.matches();
	}

	/**
	 * 验证手机号码
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkMobile(String str) {
		Pattern pattern = Pattern.compile("^1(3|4|5|7|8)\\d{9}$");
		Matcher isTrue = pattern.matcher(str);
		return isTrue.matches();
	}

	/**
	 * 验证手机号码和座机
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkTel(String str) {

		Pattern pattern = Pattern
				.compile("^1(3|4|5|7|8)\\d{9}$|^0\\d{2,3}-?\\d{7,8}$|^0\\d{2,3}-?\\d{7,8}-\\d{1,5}?$");
		Matcher isTrue = pattern.matcher(str);
		return isTrue.matches();
	}

	/**
	 * 获取订单统一流水号（主要使用）
	 */

	
}
